import React from 'react';
import { connect } from 'umi';

export const checkAuthority = (authority, currentAuthority) => {
  // 没有判定权限.默认查看所有
  if (!authority) {
    return true;
  }
  // 数组处理
  if (Array.isArray(authority)) {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.some((item) => authority.includes(item))) {
        return true;
      }
    } else if (authority.includes(currentAuthority)) {
      return true;
    }
    return false;
  }
  // string 处理
  if (typeof authority === 'string') {
    if (Array.isArray(currentAuthority)) {
      if (currentAuthority.some((item) => authority === item)) {
        return true;
      }
    } else if (authority === currentAuthority) {
      return true;
    }
    return false;
  }
  return false;
};

const Authorized = (props) => {
  const { children, authority, login, noMatch } = props;
  const {
    loginUser: { authority: currentAuthority },
  } = login;
  const childrenRender = typeof children === 'undefined' ? null : children;
  return <>{checkAuthority(authority, currentAuthority) ? childrenRender : noMatch}</>;
};

export default connect(({ login }) => ({ login }))(Authorized);
